package com.lx.javasunmmrize.JUC;

/**
 * @Description syncharonized版本生产者和消费者问题
 * AB线程,    A+1,B-1，
 * 问题： 2个线程，没问题，4个线程或更多线程还安全吗？(不安全)
 *
 * 原因:if判断可能会造成虚假唤醒
 *
 * 解决问题:使用while判断
 *
 *
 * 判断等待,业务,通知
 *
 * @Author lx
 * @Date 2021/3/2 23:32
 **/
public class PrivateConsumer01 {
    public static void main(String[] args) {
        Data data = new Data();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"A").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"B").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"C").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"D").start();
    }
}



class Data{

    private int num = 0;

    //+1
    public synchronized   void  increment() throws InterruptedException {
//        if (num!=0){
        while (num!=0){
            //等待
            this.wait();
            System.out.println(Thread.currentThread().getName()+"=========>"+num);
        }
        num++;
        //通知其他线程
        this.notify();
    }


    //-1
    public  synchronized   void  decrement() throws InterruptedException {
        while (num==0){
            //等待
            this.wait();
            System.out.println(Thread.currentThread().getName()+"=========>"+num);
        }
        num--;
        //通知其他线程
        this.notify();
    }

}